#include "gkt_debug.h"
#include "gkt_image.h"
#include "gkt_window.h"
#include "widget_draw.h"

#if defined(GKT_CONFIG_SCREEN_ENABLE) && GKT_CONFIG_SCREEN_ENABLE

static void widget_image_paint(gkt_widget_s *widget, 
				uint32_t update)
{
	const gkt_image_attr_s *image_attr;
	gkt_rect_s rect;
	uint32_t image_id;

	image_id = (widget->private_data != 0) ? 
			widget->private_data : widget->desc->attr;
	image_attr = gkt_image_get_attr(image_id);
	if (image_attr
		&& (image_attr->width > 0)
		&& (image_attr->height > 0)
		&& image_attr->data) 
	{
		rect.x = GKT_WIDGET_X(widget);
		if (image_attr->width <= GKT_WIDGET_WIDTH(widget)) {
			if (widget->flags & GKT_WIDGET_F_ALIGN_MIDDLE)
				rect.x += (GKT_WIDGET_WIDTH(widget) - image_attr->width) >> 1;
			else if (widget->flags & GKT_WIDGET_F_ALIGN_RIGHT)
				rect.x += GKT_WIDGET_WIDTH(widget) - image_attr->width;
			rect.width = image_attr->width;
		}
		else
			rect.width = GKT_WIDGET_WIDTH(widget);

		rect.y = GKT_WIDGET_Y(widget);
		if (image_attr->height <= GKT_WIDGET_HEIGHT(widget)) {
			if (widget->flags & GKT_WIDGET_F_ALIGN_CENTER)
				rect.y += (GKT_WIDGET_HEIGHT(widget) - image_attr->height) >> 1;
			else if (widget->flags & GKT_WIDGET_F_ALIGN_BOTTOM)
				rect.y += GKT_WIDGET_HEIGHT(widget) - image_attr->height;
			rect.height = image_attr->height;
		}
		else
			rect.height = GKT_WIDGET_HEIGHT(widget);
	
		widget_draw_clear(widget, 0);
		gkt_screen_draw_bitmap(image_attr->data, 
				&rect, GKT_WIDGET_FG_COLOR(widget), 
				GKT_WIDGET_BG_COLOR(widget), 0);
		if (update)
			widget_draw_update(widget);
	}
}

int gkt_widget_image_event_handler(gkt_widget_s *widget, 
					uint32_t major_type, uint32_t minor_type, 
					uint32_t data)
{
	int retval = GKT_EVENT_HANDLE_CONTINUE;

	if (GKT_EVENT_WIDGET == major_type) {
		retval = GKT_EVENT_HANDLE_COMPLETE;

		if (GKT_WIDGET_EVENT_INIT == minor_type)
			widget->private_data = 0;
		else if (GKT_WIDGET_EVENT_SHOW == minor_type)
			widget_image_paint(widget, data);
		else if (GKT_WIDGET_EVENT_HIDE == minor_type) {
			if (data & GKT_WIDGET_PAINT_EXCUTE)
				widget_draw_clear(widget, data & GKT_WIDGET_PAINT_UPDATE ? 1 : 0);
		}
		else if (GKT_WIDGET_EVENT_SET_DATA == minor_type) {
			widget->private_data = data;
			if (widget->flags & GKT_WIDGET_F_SHOW)
				widget_image_paint(widget, 1);
		}
	}
	
	return retval;
}

#endif


